package com.meeting.y.controller;

import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.core.NotAction;
import com.jfinal.core.paragetter.Para;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.swagger.annotation.ActionApi;
import com.jfinal.swagger.annotation.Api;
import com.jfinal.swagger.annotation.Param;
import com.jfinal.swagger.annotation.Params;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
import com.jfinal.wxaapp.api.WxaUserApi;
import com.meeting.y.model.*;
import com.meeting.y.util.NumberTool;
import com.meeting.y.util.RecordUtil;
import com.meeting.y.util.StringUtil;
import com.meeting.y.util.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.sql.Time;
import java.util.*;

/**
 * 因为涉及到 jfinal-weixin 版本问题，必须依赖 jfinal 3.*以上，但是JfinalQ 只有1.9
 * 所以Meeting单独项目运行，相关代码迁移至 meeging-jfinal
 */
@Api(remark="YmeetingController，小程序接口", sort=1)
public class YmeetingController extends Controller {
    private static final Logger logger = LoggerFactory.getLogger(YmeetingController.class);

    public static String _reserve_start_time = "reserve_start_time";
    public static String _reserve_end_time = "reserve_end_time";
    public static String _start_time = "start_time";
    public static String _end_time = "end_time";
    public static String _select_date_days = "select_date_days";

    public static String _alladmin = "0";

    public static DbPro getDB() {
//        return Db.use("meeting");
        return Db.use();
    }

    /**
     * userid ：wechat_user.id
     * @return
     */
    public Integer getCurrentUserId() {
        return NumberTool.safeToInteger(this.getRequest().getAttribute("userid"), -1);
    }

    /**
     * relauserid:auth_user.id
     * @return
     */
    public Integer getCurrentRelaUserId() {
        return NumberTool.safeToInteger(this.getRequest().getAttribute("relauserid"), -1);
    }

    @NotAction
    public static Integer getCurrentUserId(HttpServletRequest request){
        return NumberTool.safeToInteger(request.getAttribute("user"), -1);
    }

    @NotAction
    public static Integer getCurrentRelaUserId(HttpServletRequest request){
        return NumberTool.safeToInteger(request.getAttribute("relauserid"), -1);
    }

    public boolean getCurrentIsAdmin(Integer userid){
        if(userid == null || userid <= 0){
            userid = getCurrentRelaUserId();
        }
        if(AuthUser.dao.findById(userid) == null){
            return false;
        }
        return AuthUser.dao.findById(userid).getIsSuperuser();
    }
    @NotAction
    public static boolean getCurrentUserIsAdmin(Integer userid){
        if(AuthUser.dao.findById(userid) == null){
            return false;
        }
        return AuthUser.dao.findById(userid).getIsSuperuser();
    }

    public static Ret getConfig(String type) {
        Map _result = new HashMap();
        if ("config".equals(type)) {
            _result.put(_reserve_start_time, "08:00:00");
            _result.put(_reserve_end_time, "20:00:00");
        } else {
            _result.put(_start_time, "08:00:00");
            _result.put(_end_time, "20:00:00");
        }
        _result.put(_select_date_days, 14);
        _result.put("alladmin","1".equals(_alladmin));
        //后续全局参数，均放这里，页面调用，通过页面初始化方法，调用 this.setData({ classtypes:app.globalData.config.classtypes});
        _result.put("classtypes",MeetingEnum.dao.findMeetingenumList("classtype"));
        return Ret.create().set(_result);
    }


    /**
     * 发现这个接口 是作者后来加的，并且不是http，而是 webscoket，应该是为了增加迁移成本
     * 还好我有之前的版本，完美
     */
    @ActionKey("/wsapi")
    public void wsapi() {

        Map _result = new HashMap();
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));

    }

    /**
     * {
     * "data": {
     * "id": 6468,
     * "nickname": "",
     * "avatarurl": null,
     * "need_refresh": false
     * },
     * "code": 0,
     * "message": "返回成功"
     * }
     * 微信 相当于用户认证都帮你做好了，你直接使用用户就行了
     */
    @ActionApi(remark = "微信登录接口")
    @Params({
            @Param(name = "js_code", remark = "微信生成code", defaultValue = "微信生成", required = true)
    })
    @ActionKey("/api/wechat/login")
    public void wechat_login() {
        String js_code = getPara("js_code");
        String sessionid = getCookie("wxa-sessionid");
        //todo 新增 wechat_user，配置角色
        IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();
        String sessionJson = accessTokenCache.get("wxa:session:" + sessionid);
        Map _result = new HashMap();
        if (!StringUtil.isStrEmpty(js_code) && StrKit.isBlank(sessionJson)) {//
            WxaUserApi wxaUserApi = new WxaUserApi();
            // 获取SessionKey
            ApiResult apiResult = wxaUserApi.getSessionKey(js_code);
            logger.debug("微信接口调用，获取 apiResult-session_key:" + apiResult.getStr("session_key"));
            // 返回{"session_key":"nzoqhc3OnwHzeTxJs+inbQ==","expires_in":2592000,"openid":"oVBkZ0aYgDMDIywRdgPW8-joxXc4"}
            if (!apiResult.isSucceed()) {
                renderJson(apiResult.getJson());
                return;
            }
            String sessionKey = apiResult.getStr("session_key");
            WechatUser _wechatUser = WechatUser.dao.findWechatuserBySessionKey(sessionKey);
            if (_wechatUser != null) {
                renderJson(Ret.ok("code", 0).set("message", "返回成功")
                        .set("data", this.getUserInfo(_wechatUser)));
                return;
            }

            // 利用 appId 与 accessToken 建立关联，支持多账户
            String sessionId = StrKit.getRandomUUID();
            //将 session_key 放入 cache中
            accessTokenCache.set("wxa:session:" + sessionId, apiResult.getJson());
//            renderJson("sessionId", sessionId);
            logger.debug(" wxa:session 放入cache中，设置cookies:" + sessionId);

            setCookie("wxa-sessionid", sessionId, 15 * 24 * 3600, true);
            //        logger.info("js_code"+js_code);

            renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
            return;
        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));

    }

    @ActionApi(remark = "删除wechat_user用户")
    @Params({
            @Param(name = "user_id", remark = "wechat_user用户id", defaultValue = "-1", required = true)
    })
    @ActionKey("/api/wechatuser/delete")
    public void wechat_user_delete(){
        Integer user_id = getParaToInt("user_id");
        WechatUser.dao.delWechatuserById(user_id);
        renderJson(Ret.ok("code", 0).set("message", "返回成功"));
    }

    @ActionApi(remark = "获取枚举")
    @Params({
            @Param(name = "enumkey", remark = "枚举key", defaultValue = "classtype", required = true)
    })
    @ActionKey("/api/enum/list")
    public void enum_list(@Para("key") String key){
        List<Record> records = MeetingEnum.dao.findMeetingenumList(key);

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data",records));
    }

    @ActionApi(remark = "获取枚举")
    @Params({
            @Param(name = "enumkey", remark = "枚举key", defaultValue = "classtype", required = true)
    })
    @ActionKey("/api/enum/listarr")
    public void enum_listArr(@Para("key") String key){
        List<Record> records = MeetingEnum.dao.findMeetingenumList(key);
        Object[] arr = RecordUtil.JsontoArray(records,"name");
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data",arr));
    }

    /**
     * 微信用户信息
     * http://127.0.0.1:8000/api/wechat/user/info
     * {"data":{"id":1,"nickname":"孔令宝-携宁科技","avatarurl":"https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJBYseJziapAgJZTBWMvUUKa4k9ia4Xf747FMGKlm8NDCxcvlwPBatofxRLGXaYCvQXCdn1ziae3S6Tg/132",
     * "need_refresh":false},
     * "code":0,"message":"返回成功"}
     */
    @ActionApi(remark = "微信用户信息")
    @Params({
            @Param(name = "encrypted_data", remark = "微信生成", defaultValue = "微信生成", required = true)
    })
    @ActionKey("/api/wechat/user/info")
    public void wechat_user_info() {
        String encrypted_data = getPara("encrypted_data");
        String iv = getPara("iv");
        String sessionid = getCookie("wxa-sessionid");//后端的key
        logger.debug("获取cookies-sessionid：" + sessionid);
        sessionid = "TWaipkyiVVbeGMI4UFEvNQ==";
        if (!StringUtil.isStrEmpty(encrypted_data) && !StringUtil.isStrEmpty(sessionid)) {
            WxaUserApi wxaUserApi = new WxaUserApi();
            //test todo delete
            ApiResult apiResult = wxaUserApi.getUserInfo(sessionid, encrypted_data, iv);

            // 参数空校验 不做演示
            // 利用 appId 与 accessToken 建立关联，支持多账户
            IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();
            String sessionId = sessionid;
            if (StrKit.isBlank(sessionId)) {
                Kv data = Kv.by("errcode", 500)
                        .set("errmsg", "wxa_session Header is blank");
                renderJson(data);
                return;
            }
            String sessionJson = accessTokenCache.get("wxa:session:" + sessionId);
            if (StrKit.isBlank(sessionJson)) {
                Kv data = Kv.by("errcode", 500)
                        .set("errmsg", "wxa_session sessionJson is blank");
                renderJson(data);
                return;
            }
            logger.debug("Cache中获取-sessionJson:" + sessionJson);
            ApiResult sessionResult = ApiResult.create(sessionJson);
            // 获取sessionKey
            String sessionKey = sessionResult.get("session_key");
            logger.debug("session_key:" + sessionKey);
            if (StrKit.isBlank(sessionKey)) {
                Kv data = Kv.by("errcode", 500)
                        .set("errmsg", "sessionKey is blank");
                renderJson(data);
                return;
            }
            WechatUser _wechatUser = WechatUser.dao.findWechatuserBySessionKey(sessionKey);
            if (_wechatUser != null) {
                renderJson(Ret.ok("code", 0).set("message", "返回成功")
                        .set("data", this.getUserInfo(_wechatUser)));
                return;
            }

            String rawData = getPara("rawData");
            // 用户信息校验
            if (!StringUtil.isStrEmpty(rawData)) {// todo 待明确用途
                //通过 sessionKey，去解析数据，获取用户信息
                boolean check = wxaUserApi.checkUserInfo(sessionKey, rawData, iv);
                if (!check) {
                    Kv data = Kv.by("errcode", 500)
                            .set("errmsg", "UserInfo check fail");
                    renderJson(data);
                    return;
                }
            }
            // 服务端解密用户信息
            ApiResult apiResult1 = wxaUserApi.getUserInfo(sessionKey, encrypted_data, iv);
            if (!apiResult1.isSucceed()) {
                logger.info("isSucceed:"+apiResult1.isSucceed());
                renderJson(apiResult1.getJson());
                return;
            }
            // 如果开发者拥有多个移动应用、网站应用、和公众帐号（包括小程序），可通过unionid来区分用户的唯一性
            // 同一用户，对同一个微信开放平台下的不同应用，unionid是相同的。
            String unionId = apiResult1.get("unionId");
/**
 * {"openId":"oo4fI5fQG0sbGJxFI0g3azGgMBzA",
 * "nickName":"孔令宝-携宁科技","gender":1,"language":"zh_CN","city":"徐汇","province":"上海","country":"中国",
 * "avatarUrl":"https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJBYseJziapAgJZTBWMvUUKa4k9ia4Xf747FMGKlm8NDCxcvlwPBatofxyHwqPXnN0u12RvhK2X1pLA/132",
 * "watermark":{"timestamp":1571119870,"appid":"wxaf9a125026464d06"}}
 */
            String openid = apiResult1.get("openId");
            WechatUser wechatUser = WechatUser.dao.findWechatuser(openid);
            if (wechatUser == null) {
                wechatUser = new WechatUser();
            }
            wechatUser.setSessionKey(sessionKey);
            wechatUser.setNickname(apiResult1.getStr("nickName"));
            wechatUser.setAvatarurl(apiResult1.getStr("avatarUrl"));
            wechatUser.setCity(apiResult1.getStr("city"));
            wechatUser.setGender(apiResult1.getInt("gender"));
            wechatUser.setLanguage(apiResult1.getStr("language"));
            wechatUser.setCountry(apiResult1.getStr("country"));
            wechatUser.setProvince(apiResult1.getStr("province"));
            wechatUser.setMobile(StringUtil.valueOf(apiResult1.getStr("mobile")));
            wechatUser.setOpenid(apiResult1.getStr("openId"));
            if (wechatUser.getNickname().equals("孔令宝-携宁科技") ||
                    wechatUser.getNickname().equals("冷丁")) {
                wechatUser.setRelaUserId(1);
                wechatUser.setRelaUserDesc("管理员");
            }
            wechatUser.setUnionid(StringUtil.valueOf(unionId));
            wechatUser.setModifyTime(new Date());
            if (wechatUser.getId() == null) {
                wechatUser.save();
                try {
                    Record user = new Record();
                    user.set("userid", wechatUser.getId()); //wechat_user.id = user.userid
                    user.set("avatarUrl", wechatUser.getAvatarurl());
                    user.set("city", wechatUser.getCity());
                    user.set("country", wechatUser.getCountry());
                    user.set("credit", 0);//积分
                    user.set("gender", wechatUser.getGender());
                    user.set("nickName", wechatUser.getNickname());
                    user.set("openid", wechatUser.getOpenid());
                    user.set("province", wechatUser.getProvince());
                    user.set("sessionKey", wechatUser.getSessionKey());
                    PaperDao.dao.saveUser(user);
                }catch (Exception e){
                    logger.error("同步用户到user报错",e);
                }
            } else {
                wechatUser.update();
            }

// 下方为模拟数据：
            logger.info("encrypted_data:"+encrypted_data);

            renderJson(Ret.ok("code", 0).set("message", "返回成功")
                    .set("data", this.getUserInfo(wechatUser)));
            return;
        }
        Map _result = new HashMap();

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));

    }

    /**
     * 首页用户信息
     * "code":0,"message":"返回成功"}
     */
    @ActionApi(remark = "小程序首页，课时统计，管理员可选人")
    @Params({
            @Param(name = "month", remark = "月，默认当月，加减几个月", defaultValue = "-1"),
            @Param(name = "classrelaid", remark = "用户id，方方", defaultValue = "1741")
    })
    @ActionKey("/api/user/classinfo")
    public void user_classInfo() {
        Integer month = getParaToInt("month",0);
        Integer current = getParaToInt("classrelaid",0);
        if(current <= 0) {
            current = getCurrentRelaUserId();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH,month);
        Date fromdate = TimeUtil.getFirstDateOfMonth(calendar.getTime());
        Date todate = TimeUtil.getLastDateOfMonth(calendar.getTime());
        AuthUser authUser = AuthUser.dao.findById(current);
        Record _result = new Record();
        if(authUser!=null || "1".equals(_alladmin)){
            //预计:{{classinfo.all}}　　已上:{{classinfo.done}}　　待上:{{classinfo.will}}
            //其中 一对一:{{classinfo.ydy}}　　秋季班:{{classinfo.qjb}}　　团体班:{{classinfo.ttb}}
            //师假:{{classinfo.teacleave}}　　生假:{{classinfo.studleave}}
            //小程序 list.js :
            // {key:'done',name:'已上'},{key:'will',name:'待上'},{key:'ydy',name:'一对一'},{key:'qjb',name:'秋季班'},
            // {key:'ttb',name:'团体班'},{key:'teacleave',name:'师假'},{key:'studleave',name:'生假'}
            _result = MeetingsMeeting.dao.countMeetings(fromdate,todate,current);
        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }

    @ActionKey("/api/meeting/list")
    public void meeting_list(){
        Ret ret = Ret.create();
        Integer month = getParaToInt("month",0);
        Integer current = getParaToInt("classrelaid",0);
        List<String> searchtype = Arrays.asList(getPara("searchtype","").split(","));
        if(current <= 0) {
            current = getCurrentRelaUserId();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH,month);
        Date fromdate = TimeUtil.getFirstDateOfMonth(calendar.getTime());
        Date todate = TimeUtil.getLastDateOfMonth(calendar.getTime());
        AuthUser authUser = AuthUser.dao.findById(current);
        if(authUser!=null || "1".equals(_alladmin)) {
            List<Record> meetings = MeetingsMeeting.dao.countMeetingsRecords(fromdate,todate,current,searchtype);
            ret.set("meetings", meetings);
            Map _info = new HashMap();
            _info.put("name",authUser.getFirstName() +" 月度展示");
            _info.put("role",authUser.getRole());
            _info.put("description",authUser.getRemark());
            ret.set("info", _info);
        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", ret));
    }

    /**
     * 首页用户信息
     * "code":0,"message":"返回成功"}
     */
    @ActionKey("/api/user/info")
    public void user_info() {
        Map _result = new HashMap();
        AuthUser authUser = AuthUser.dao.findById(getCurrentRelaUserId());
        if (authUser == null) {
            WechatUser wechatUser = WechatUser.dao.findById(getCurrentUserId());
            if(wechatUser == null || wechatUser.getDeleteStatus()){//删除状态待确认
                _result.put("showrightbtn", 1);//微信授权按钮显示，还有一种可能 授权过期，重新login
            }else {
                _result.put("id", "W"+wechatUser.getId());
                _result.put("userid", getCurrentUserId());
                _result.put("name", wechatUser.getNickname());
                _result.put("role", "待申请");
                _result.put("showinput", 1);
                _result.put("showrightbtn", 0);
                String s = null;
                if(wechatUser.getRemark() != null) {
                    s = new String(wechatUser.getRemark());
                }
                _result.put("approvetext", s);
                if(_alladmin.equals("1")){//针对未注册用户开启管理员模式
                    _result.put("role", "管理员");
                    _result.put("showinput", 0);//管理员模式下，无需提交申请
                }
            }
        } else {
            _result.put("id", "U"+authUser.getId());
            _result.put("userid", getCurrentUserId());
            _result.put("name", authUser.getFirstName());
            _result.put("open_paper", authUser.getOpenPaper());
            _result.put("classfee", authUser.getClassfee());
            _result.put("is_superuser", authUser.getIsSuperuser());
            _result.put("role", authUser.getRole());
            _result.put("showinput", 0);
            _result.put("showrightbtn", 0);
        }
        MeetingEnum meetingEnum = MeetingEnum.dao.findMeetingenum("alladmin");
        if(meetingEnum != null) {
            setCookie("alladmin", meetingEnum.getMeetingEnumVal(), 15 * 24 * 3600, true);
            _alladmin = meetingEnum.getMeetingEnumVal();
        }
        _result.put("date", TimeUtil.getCurrentDate("yyyy-MM-dd HH:mm"));
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));

    }

    @ActionKey("/api/user/edit/info")
    public void user_edit_info() {
        Map _result = new HashMap();
        AuthUser authUser = AuthUser.dao.findById(getParaToInt("relaid"));
        if (authUser != null) {
            _result.put("name", authUser.getFirstName());
            _result.put("role", authUser.getRole());
            _result.put("default_roomid", authUser.getDefaultRoomid());
            _result.put("is_active", authUser.getIsActive());
            _result.put("open_paper", authUser.getOpenPaper());
            _result.put("classfee", authUser.getClassfee());
            _result.put("is_superuser", authUser.getIsSuperuser());

        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }

    @ActionKey("/api/user/edit/save")
    public void user_edit_save() {
        Map _result = new HashMap();
        AuthUser authUser = AuthUser.dao.findById(getParaToInt("relaid"));
        if (authUser == null) {
            authUser = new AuthUser();
        }
        authUser.setFirstName(getPara("name"));
        authUser.setUsername(getPara("name"));
        authUser.setRole(getPara("role"));
        authUser.setDefaultRoomid(NumberTool.safeToInteger(getPara("default_roomid"),-1));
        authUser.setClassfee(NumberTool.safeToInteger(getPara("classfee"),-1));
        authUser.setIsActive(getParaToBoolean("is_active"));
        authUser.setOpenPaper(getParaToBoolean("open_paper")?1:0);
        authUser.setIsSuperuser(getParaToBoolean("is_superuser"));
        authUser.setRemark(getPara("remark"));
        AuthUser.dao.saveOrUpdate(authUser);
        _result.put("name", authUser.getFirstName());
        _result.put("role", authUser.getRole());
        _result.put("default_roomid", authUser.getDefaultRoomid());
        _result.put("is_active", authUser.getIsActive());
        _result.put("remark", authUser.getRemark());

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }

    @ActionKey("/api/user/approve")
    public void user_approve() {
        Map _result = new HashMap();
        WechatUser wechatUser = WechatUser.dao.findById(getCurrentUserId());
        if (wechatUser != null) {
            String _approve = getPara("approvetext");
            if(_approve.length()>30){
                _approve = _approve.substring(0,30);
            }
            wechatUser.setRemark(_approve.getBytes());
            wechatUser.update();
        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }

    /**
     * 用户列表 type：rela、norela
     */
    @ActionKey("/api/user/list")
    public void user_list() {
        String _type = getPara("type");
        String _searchkey = getPara("searchkey");
        logger.debug("--------------------_searchkey:"+_searchkey);
        logger.debug("--------------------_searchkey:"+_searchkey);
        List<Record> _result = WechatUser.dao.findWechatuserByType(_type, _searchkey);
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }

    /**
     * 用户搜索框 type：rela、norela
     */
    @ActionKey("/api/user/find")
    public void user_find() {
        String input = getPara("input");
        Integer surveyid = getParaToInt("surveyid",-1);
        logger.debug("--------------------_searchkey:"+input);
        logger.debug("--------------------surveyid:"+surveyid);
        List<Record> _result = null;
        if(surveyid < 0) {
            _result = AuthUser.dao.findByName(input);
        }else {
            _result = AuthUser.dao.findByNameSurvey(input, surveyid);
        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }

    /**
     * 用户保存关联
     */
    @ActionKey("/api/user/deleterela")
    public void user_deleterela() {
        Integer user_id = getParaToInt("user_id");
        WechatUser wechatUser = WechatUser.dao.findById(user_id);
        wechatUser.setRelaUserId(null);
        wechatUser.setRelaUserDesc(null);
        wechatUser.update();
        renderJson(Ret.ok("code", 0).set("message", "返回成功"));
    }

    /**
     * 用户保存关联
     */
    @ActionKey("/api/paper/rightinfo")
    public void paper_rightinfo() {
        Integer surveyid = getParaToInt("surveyid");
        String _relatable = "survey";
        List<Record> _result = MeetingUserRela.dao.findUserName(null,surveyid,_relatable,"1");
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }
    /**
     * 用户保存关联
     */
    @ActionKey("/api/paper/rightsave")
    public void paper_rightsave() {
        String userids = getPara("userids");
        Integer surveyid = getParaToInt("surveyid");
        String _relatable = "survey";
        Integer count = MeetingUserRela.dao.findCount(null,surveyid,_relatable,"1");
        if(count != null && count>0){
            MeetingUserRela.dao.deleteRela(null,surveyid,_relatable,"1");
        }

        for(String userid : userids.split(",")) {
            MeetingUserRela meetingUserRela = new MeetingUserRela();
            meetingUserRela.setModifyTime(new Date());
            meetingUserRela.setUserId(NumberTool.safeToInteger(userid,-1));
            meetingUserRela.setRelaId(surveyid);
            meetingUserRela.setRelaTable(_relatable);
            meetingUserRela.setRelaType("1");//有权限
            meetingUserRela.setCreateUserId(getCurrentRelaUserId());
            meetingUserRela.dao.saveOrUpdateMeetinguserrela(meetingUserRela);

        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功"));
    }


    /**
     * 用户保存关联
     */
    @ActionKey("/api/user/saverela")
    public void user_saverela() {
        Integer user_id = getParaToInt("user_id");
        Integer relaid = getParaToInt("relaid");
        String rela_user_desc = getPara("rela_user_desc");
        WechatUser wechatUser = WechatUser.dao.findById(user_id);
        wechatUser.setRelaUserId(relaid);
        wechatUser.setRelaUserDesc(rela_user_desc);
        wechatUser.update();
        renderJson(Ret.ok("code", 0).set("message", "返回成功"));
    }

    /**
     * 用户详情
     */
    @ActionKey("/api/user/advise/list")
    public void user_adviselist() {
        Map _result = new HashMap();
        Integer statussearch = getParaToInt("statussearch");
        Integer userid = getCurrentRelaUserId();
        String _role = "";
        if (userid <= 0){
            _role = "待申请";
        }else {
            AuthUser authUser = AuthUser.dao.findById(userid);
            if (authUser!=null){
                if(authUser.getIsSuperuser()){
                    _role = "管理员";
                }else {
                    _role = authUser.getRole();
                }
            }
        }
        if(_alladmin.equals("1")) {//针对未注册用户开启管理员模式
            _role = "管理员";
        }
        _result.put("role",_role);
        if(_role.equals("管理员")){
            userid = 0;
        }
        List<Record> list = MeetingEnum.dao.findMeetingEnum(statussearch,userid);
        _result.put("adviselist",list);
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }


    /**
     * 用户详情
     */
    @ActionKey("/api/user/advise/save")
    public void user_saveadvise() {
        String approvetext = getPara("approvetext");
        Integer id = getParaToInt("id",0);
        Integer status = getParaToInt("status");
        if(id>0){
            MeetingEnum meetingEnum =  MeetingEnum.dao.findById(id);
            meetingEnum.setMeetingEnumVal(status+"");
            if(status !=null && status == 7){
                meetingEnum.setDeleteStatus(true);
            }
            meetingEnum.update();
        }else{
            MeetingEnum meetingEnum =  new MeetingEnum();
            meetingEnum.setMeetingEnumVal(1+"");
            meetingEnum.setMeetingEnumKey("advise");
            meetingEnum.setUserId(getCurrentRelaUserId());
            meetingEnum.setMeetingEnumShowname(approvetext);
            meetingEnum.setModifyTime(new Date());
            meetingEnum.setMeetingEnumSort("1");
            meetingEnum.save();
        }

        renderJson(Ret.ok("code", 0).set("message", "返回成功"));
    }

    /**
     * 用户详情
     */
    @ActionKey("/api/user/intoclass/list")
    public void user_intoclasslist() {
        Map _result = new HashMap();

        Integer userid = getCurrentRelaUserId();
        String _role = "";
        if (userid <= 0){
            _role = "待申请";
        }else {
            AuthUser authUser = AuthUser.dao.findById(userid);
            if (authUser!=null){
                if(authUser.getIsSuperuser()){
                    _role = "管理员";
                }else {
                    _role = authUser.getRole();
                }
            }
        }
        if(_alladmin.equals("1")) {//针对未注册用户开启管理员模式
            _role = "管理员";
        }
        _result.put("role",_role);

        String classperiod = getPara("period");
        if(StringUtil.isStrEmpty(classperiod)) {
            classperiod = getSeason(new Date(), 93);
        }
        //查找所有状态的数据，下个季度
        List<Record> list = MeetingClassOrder.dao.findMeetingclassorderList(classperiod);
        _result.put("adviselist",list);

        String now_classperiod = getSeason(new Date(),0);
        //现在自己当前季度情况
        MeetingClassOrder meetingClassOrder = MeetingClassOrder.dao.findMeetingclassorder(userid,now_classperiod);
        //页面 todo 显示效果
        _result.put("order",meetingClassOrder);

        List<String> listclassperiod = new ArrayList<>();
        for(int i = 0;i<=3 ;i++){
            listclassperiod.add(getSeason(new Date(),i*93));
        }
        _result.put("classperiod",listclassperiod.toArray(new String [0]));


        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }

    public static String getSeason(Date indate,int days){
        Date date = TimeUtil.getPreOrNextDay(indate,days);
        int season = TimeUtil.getSeason(date);
        String year = TimeUtil.formatDate(date,"yyyy");
        return year+"0"+season;
    }


    /**
     * 用户详情
     */
    @ActionKey("/api/user/intoclass/save")
    public void user_saveintoclass() {
        String approvetext = getPara("approvetext");
        String classperiod = getPara("classperiod");
        Integer id = getParaToInt("id",0);
        Integer status = getParaToInt("status",1);
        Integer userid = getCurrentRelaUserId();
        int max = MeetingClassOrder.dao.findMaxOrder();
        if(id>0){
            MeetingClassOrder classOrder =  MeetingClassOrder.dao.findById(id);
            classOrder.setRemark(approvetext);
            classOrder.setUserId(userid);
            classOrder.setModifyTime(new Date());
            classOrder.setClassPeriod(classperiod);
            classOrder.setStatus(status);
            classOrder.update();
        }else{
            MeetingClassOrder classOrder =  new MeetingClassOrder();
            classOrder.setRemark(approvetext);
            classOrder.setUserId(userid);
            classOrder.setModifyTime(new Date());
            classOrder.setClassOrder(max+1);
            classOrder.setClassPeriod(classperiod);
            classOrder.setStatus(status);
            classOrder.setCreateUserId(userid);
            classOrder.save();
        }

        renderJson(Ret.ok("code", 0).set("message", "返回成功"));
    }

    /**
     * 用户详情
     */
    @ActionKey("/api/user/detail")
    public void user_detail() {
        Map _result = new HashMap();
        Integer _id = getParaToInt("user_id");
        WechatUser wechatUser = WechatUser.dao.findById(_id);
        if(wechatUser!=null) {
            _result.put("name", wechatUser.getNickname());
            _result.put("description", StringUtil.byte2Str(wechatUser.getRemark()));
            Integer _relauserid = wechatUser.getRelaUserId();
            if (_relauserid != null) {
                _result.put("rela_user_id", _relauserid);
                _result.put("rela_user_desc", wechatUser.getRelaUserDesc());
                AuthUser authUser = AuthUser.dao.findById(_relauserid);
                _result.put("role", authUser.getRole());
                _result.put("role_name", authUser.getFirstName());
            }
        }

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }


    public Map getUserInfo(WechatUser wechatUser) {
        Map _result = new HashMap();
        _result.put("id", wechatUser.getId());
        _result.put("nickname", wechatUser.getNickname());
        _result.put("avatarurl", wechatUser.getAvatarurl());
        _result.put("need_refresh", false);
        if(wechatUser.getRelaUserId() !=null) {
            AuthUser user = AuthUser.dao.findAuthuserById(wechatUser.getRelaUserId());
            _result.put("is_superuser",user.getIsSuperuser());
            _result.put("open_paper",new Integer(1).equals(user.getOpenPaper()));
        }else{
            _result.put("is_superuser",false);
            _result.put("open_paper",false);
        }
        //问卷用到的id
        _result.put("userid", WechatUser.dao.getPaperUseridByOpenid(wechatUser.getOpenid()));
        return _result;
    }

    /**
     * 会议配置信息
     * {
     * "data": {
     * "reserve_start_time": "07:00:00",
     * "reserve_end_time": "22:30:00",
     * "select_date_days": 19,
     * "banner_ad_unit_id": "adunit-8bbcd17425bb250c",
     * "banner_ad_intervals": 30
     * },
     * "code": 0,
     * "message": "返回成功"
     * }
     */
    @ActionKey("/api/meeting/config")
    public void meeting_config() {

//        _result.put("banner_ad_unit_id","adunit-8bbcd17425bb250c");
//        _result.put("banner_ad_intervals",30);

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", getConfig("config")));

    }

    @ActionKey("/api/meeting/config/save")
    public void meeting_configsave() {
        MeetingEnum meetingEnum = MeetingEnum.dao.findMeetingenum("alladmin");
        boolean alladmin = getParaToBoolean("alladmin");
        if(alladmin){
            meetingEnum.setMeetingEnumVal("1");
        }else {
            meetingEnum.setMeetingEnumVal("0");
        }
        meetingEnum.update();
        _alladmin = meetingEnum.getMeetingEnumVal();
        renderJson(Ret.ok("code", 0).set("message", "返回成功"));

    }

    /**
     * 参与的会议室
     */
    @ActionKey("/api/meeting/follow/rooms")
    public void meeting_follow_rooms() {
        Integer userid = getCurrentRelaUserId();
        List<Record> _result =
//                关注 改为 参与
//                YMeetingModel.dao.findRooms(null, Ret.create().set("b.user_id", userid));
        YMeetingModel.dao.findAttendMeetingRooms(null, Ret.create().set("b.user_id", userid));
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }

    /**
     * 我创建的会议室
     */
    @ActionKey("/api/meeting/create/rooms")
    public void meeting_create_rooms() {
        Integer userid = getCurrentUserId();
        List<Record> _result = Db.find("select * from meetings_room a where a.create_user_id =? and a.delete_status=0", userid);
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }

    /**
     * 我的会议
     * {"data":{"start_time":"07:00:00","end_time":"22:30:00","start_date":"2019-10-13","end_date":"2019-11-01",
     * "rooms":[{"id":4,"name":"会议室101","description":"描述334"}],
     * "meetings":[{"id":6,"user":1,"room":4,"date":"2019-10-14","start_time":"10:30:00","end_time":"12:00:00","name":"ju","description":"111"}]},
     * "code":0,"message":"返回成功"}
     */
//    @ActionKey("/api/meeting/my/meetings?date=")
    @ActionKey("/api/meeting/my/meetings")
    public void meeting_my_meetings() {
        Date date = TimeUtil.getAroundWeekFirst(getParaToInt("week"));
//        TimeUtil.formatDate(TimeUtil.getCurrentDate("yyyy-MM-dd"), "yyyy-MM-dd");
        Integer userid = getCurrentRelaUserId();
        Ret ret = Ret.create().set(getConfig(""));
        ret.set("start_date", TimeUtil.formatDate(date, "yyyy-MM-dd"));
        ret.set("end_date", TimeUtil.formatDate(TimeUtil.addDays(date, getConfig("").getInt(_select_date_days)), "yyyy-MM-dd"));
        //todo 我参加会议的会议室
        //管理员，可以看到 全部有效的

        List<Record> rooms = new ArrayList<>();
        if(getCurrentIsAdmin(null)){
            rooms = MeetingsRoom.dao.findAllMeetingsroom();
        }else {
            rooms = MeetingsRoom.dao.findMeetingsRoomRecord(userid);
        }
//        List<Record> roomsfollow = YMeetingModel.dao.findRooms(null, Ret.create().set("b.user_id", userid));
        List<Record> roomsadd = YMeetingModel.dao.findAttendMeetingRooms(null, Ret.create().set("b.user_id", userid));
//        rooms.addAll(roomsfollow);
        rooms.addAll(roomsadd);
        //去重
        List<Record> _result = RecordUtil.Set(rooms, "");
        ret.set("rooms", _result);
        //todo 会议室的会议
        date = getParaToDate("date", date);
        String rightsql = getAttr("rightsql","");
        Log.getLog(this.getClass()).debug("---------"+userid+TimeUtil.formatDate(date,"yyyy-MM-dd HH:mm:ss")+rightsql);
        List<Record> meetings = MeetingsMeeting.dao.findMeetingsmeetingByRoomAtt(userid, date,rightsql);
        ret.set("meetings", meetings);
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", ret));
    }

    /**
     * 新增会议室
     */
//    @ActionKey("/api/meeting/room/create?name= 会议室1012&description= 描述2&create_user_manager= true")
    @ActionKey("/api/meeting/room/create")
    public void meeting_room_create() {
        String name = getPara("name");
        String desc = getPara("description");
        Boolean create_user_manager = getParaToBoolean("create_user_manager");
        MeetingsRoom meetingsRoom = new MeetingsRoom();
        meetingsRoom.setName(name);
        meetingsRoom.setDescription(desc);
        meetingsRoom.setCreateUserManager(create_user_manager);
        meetingsRoom.setModifyTime(new Date());
        meetingsRoom.setQrCode("");
        meetingsRoom.setCreateUserId(getCurrentUserId());
        meetingsRoom.save();
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", meetingsRoom));
    }

    /**
     * 编辑会议室
     */
//    @ActionKey("/api/meeting/room/edit?room_id= 4&name= 会议室101&description= 描述334&create_user_manager= true")
    @ActionKey("/api/meeting/room/edit")
    public void meeting_room_edit() {
        Integer id = getParaToInt("room_id");
        String name = getPara("name");
        String desc = getPara("description");
        Boolean create_user_manager = getParaToBoolean("create_user_manager");
        MeetingsRoom meetingsRoom = MeetingsRoom.dao.findById(id);
        if (meetingsRoom == null) {
            renderJson(Ret.ok("code", 1).set("message", "更新失败-未找到对象"));
            return;
        }
        meetingsRoom.setName(name);
        meetingsRoom.setDescription(desc);
        meetingsRoom.setCreateUserManager(create_user_manager);
        meetingsRoom.update();
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", meetingsRoom));
    }

    /**
     * 会议室明细
     * {"data":
     * {"id":1,"name":"121","description":"1212","qr_code":null,"create_user":1,"is_follow":true,
     * "create_user_manager":false}
     * ,"code":0,"message":"返回成功"}
     */
//    @ActionKey("/api/meeting/room/info?room_id=1")
    @ActionKey("/api/meeting/room/info")
    public void meeting_room_info() {
        //todo 通过session 获取当前用户信息
        Integer currentUserid = getCurrentUserId();

        Integer room_id = getParaToInt("room_id");
        Record _result = getDB().findFirst("select a.create_user_id create_user,a.*," +
                        "(select count(1)>0 from meetings_userfollowroom where room_id = ? and user_id = ? ) is_follow" +
                        " from meetings_room a where id=?",
                room_id, currentUserid, room_id);
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }

    /**
     * 会议列表
     * {"data":{"start_time":"07:00:00","end_time":"22:30:00","start_date":"2019-10-13","end_date":"2019-11-01",
     * "rooms":[{"id":4,"name":"会议室101","description":"描述334"},{"id":7,"name":"测试用户新增","description":"测试"}],
     * "meetings":[{"id":6,"user":1,"room":4,"date":"2019-10-14","start_time":"10:30:00","end_time":"12:00:00","name":"ju","description":"111"}]},
     * "code":0,"message":"返回成功"}
     */
//    @ActionKey("/api/meeting/room/meetings?room_ids=1&date=")
    @ActionKey("/api/meeting/room/meetings")
    public void meeting_room_meetings() {
        Date _defaultDate = TimeUtil.getAroundWeekFirst(getParaToInt("week"));
//        Date _defaultDate = TimeUtil.formatDate(TimeUtil.getCurrentDate("yyyy-MM-dd"), "yyyy-MM-dd");
        String room_ids = getPara("room_ids");

        Integer userid = getCurrentUserId();
        Ret ret = Ret.create().set(getConfig(""));
        ret.set("start_date", TimeUtil.formatDate(_defaultDate, "yyyy-MM-dd"));
        ret.set("end_date", TimeUtil.formatDate(TimeUtil.addDays(_defaultDate, getConfig("").getInt(_select_date_days)), "yyyy-MM-dd"));

        Date date = getParaToDate("date", _defaultDate);//todo 确定格式, 展示列表 不变，都是19天，data 用来查询数据
        //todo 我参加会议的会议室
        List<Record> rooms = new ArrayList<>();
        for (String id : room_ids.split(",")) {
            Integer _id = NumberTool.safeToInteger(id, 0);
            rooms.add(MeetingsRoom.dao.findById(_id).toRecord());
        }
        ret.set("rooms", rooms);
        //todo 会议室的会议
        String rightsql = getAttr("rightsql","");
        List<Record> meetings = MeetingsMeeting.dao.findMeetingsmeetingByRoom(room_ids, date,rightsql);
        ret.set("meetings", meetings);
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", ret));

    }

    /**
     * 关注的会议室
     */
//    @ActionKey("/api/meeting/room/follow?room_id=5")
    @ActionKey("/api/meeting/room/follow")
    public void meeting_room_follow() {
        Integer room_id = getParaToInt("room_id");
        Integer userid = getCurrentUserId();
        MeetingsUserfollowroom meetingsUserfollowroom = new MeetingsUserfollowroom();
        meetingsUserfollowroom.setRoomId(room_id);
        meetingsUserfollowroom.setUserId(userid);
        meetingsUserfollowroom.setModifyTime(new Date());
        meetingsUserfollowroom.save();
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", meetingsUserfollowroom));

    }

    /**
     * 取消关注会议室
     */
//    @ActionKey("/api/meeting/room/un/follow?room_id=5")
    @ActionKey("/api/meeting/room/un/follow")
    public void meeting_room_un_follow() {
        Integer room_id = getParaToInt("room_id");
        Integer userid = getCurrentUserId();
        List<MeetingsUserfollowroom> meetingsUserfollowroom =
                MeetingsUserfollowroom.dao.findMeetingsuserfollowroom(userid, room_id);
        if (meetingsUserfollowroom.size() > 0) {
            for (MeetingsUserfollowroom meetingsUserfollowroom1 : meetingsUserfollowroom) {
                MeetingsUserfollowroom.dao.delMeetingsuserfollowroomById(meetingsUserfollowroom1.getId().intValue());
            }
        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功"));
    }

    /**
     * 删除会议室
     */
//    @ActionKey("/api/meeting/room/delete?room_id=5")
    @ActionKey("/api/meeting/room/delete")
    public void meeting_room_delete() {
        Integer room_id = getParaToInt("room_id");
        MeetingsRoom.dao.delMeetingsroomById(room_id);
        renderJson(Ret.ok("code", 0).set("message", "返回成功"));
    }

    /**
     * 预约会议-新增
     */
//    @ActionKey("/api/meeting/reserve?room_id= 1&name= 3434-key&description= 33&
//      date= 2019-08-07&start_time= 07:00&end_time= 08:00")
    @ActionKey("/api/meeting/reserve")
    public void meeting_reserve(MeetingsMeeting m) {
        Integer room_id = getParaToInt("room_id");
        String name = getPara("name");
        String desc = getPara("description");
        Date date = getParaToDate("date");//todo 确定格式
        Date start_time = TimeUtil.formatDate(
                getPara("date") + " " + getPara("start_time"), "yyyy-MM-dd HH:mm");
        Date end_time = TimeUtil.formatDate(
                getPara("date") + " " + getPara("end_time"), "yyyy-MM-dd HH:mm");
//         m = new MeetingsMeeting();
        m.setName(name);
        m.setDate(date);
        m.setStartTime(start_time);
        m.setEndTime(end_time);
        m.setRoomId(room_id);
        m.setDescription(desc);
        m.setModifyTime(new Date());
        m.setUserId(getCurrentUserId());
        m.save();

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", m));
    }


    /**
     * 课程 状态
     * "code":0,"message":"返回成功"}
     */
    @ActionKey("/api/meeting/classstatus")
    public void meeting_classStatus() {
        Integer current = getParaToInt("meeting_id",0);
        Integer classstatus = getParaToInt("classstatus",0);

        MeetingsMeeting meetingsMeeting = MeetingsMeeting.dao.findById(current);
        Map _result = new HashMap();
        if(meetingsMeeting!=null ){
            meetingsMeeting.setClassStatus(classstatus);
            meetingsMeeting.update();
        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }

    public void meeting_update(){
        Integer current = getParaToInt("meeting_id",0);

        MeetingsMeeting meetingsMeeting = MeetingsMeeting.dao.findById(current);
        Map _result = new HashMap();

        Integer isOwed = getParaToInt("isOwed",0);
        if(meetingsMeeting!=null && isOwed>0){
            String owedNo = getPara("owedno");
            String owedpatchno = getPara("owedpatchno");
            meetingsMeeting.setIsOwed(isOwed);
            meetingsMeeting.setOwedNo(owedNo);
            meetingsMeeting.setOwedpatchNo(owedpatchno);
            meetingsMeeting.update();
        }

        Integer classtype = getParaToInt("classtype",0);
        if(meetingsMeeting!=null && isOwed>0){
            meetingsMeeting.setType(classtype+"");
            meetingsMeeting.update();
        }

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }


    /**
     * 编辑会议
     */
//    @ActionKey("/api/meeting/edit?meeting_id= 4&name= 参数测试&description= 测试3355")
    @ActionKey("/api/meeting/edit")
    public void meeting_edit(MeetingsMeeting m) {
        Integer meeting_id = getParaToInt("meeting_id");
        String name = getPara("name");
        String desc = getPara("description");
        Double weight = NumberTool.safeToDouble(getPara("weight"),1.0);
//         m = new MeetingsMeeting();\
        m = MeetingsMeeting.dao.findById(meeting_id);
        m.setName(name);
        m.setDescription(desc);
        m.setModifyTime(new Date());
        m.setWeight(weight);
        m.update();
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", m));

    }

    /**
     * 会议信息
     * http://127.0.0.1:8000/api/meeting/info?meeting_id=5
     * {"data":{"id":5,
     * "user":{"id":1,"nickname":"孔令宝-携宁科技","avatarurl":"https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJBYseJziapAgJZTBWMvUUKa4k9ia4Xf747FMGKlm8NDCxcvlwPBatofxRLGXaYCvQXCdn1ziae3S6Tg/132","need_refresh":false},
     * "room":{"id":1,"name":"121","description":"1212"},
     * "date":"2019-10-14",
     * "start_time":"09:00:00",
     * "end_time":"11:00:00",
     * "attendees":[
     * {"id":1,"nickname":"孔令宝-携宁科技","avatarurl":"https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJBYseJziapAgJZTBWMvUUKa4k9ia4Xf747FMGKlm8NDCxcvlwPBatofxRLGXaYCvQXCdn1ziae3S6Tg/132","need_refresh":false}
     * ],
     * "name":"huiyi1","description":"deschuiyi","is_manager":true},
     * "code":0,"message":"返回成功"}
     */
//    @ActionKey("/api/meeting/info?meeting_id=3")
    @ActionKey("/api/meeting/info")
    public void meeting_info() {
        Integer meeting_id = getParaToInt("meeting_id");
        MeetingsMeeting m = MeetingsMeeting.dao.findById(meeting_id);
        Record record = m.toRecord();
        record.set("user", AuthUser.dao.findRcById(m.getUserId()));
        record.set("room", MeetingsRoom.dao.findById(m.getRoomId()));
        record.set("date", TimeUtil.formatDate(m.getDate(), "yyyy-MM-dd"));
        record.set("is_manager", m.getUserId().equals(getCurrentUserId()));
        record.set("start_time", TimeUtil.formatDate(m.getStartTime(), "HH:mm"));
        record.set("end_time", TimeUtil.formatDate(m.getEndTime(), "HH:mm"));
        record.set("weight",m.getWeight());
        record.set("attendees", AuthUser.dao.findAttendUserByMeetingid(meeting_id));
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", record));

    }

    /**
     * 取消会议
     */
//    @ActionKey("/api/meeting/cancel?meeting_id=3")
    @ActionKey("/api/meeting/cancel")
    public void meeting_cancel() {
        Integer meeting_id = getParaToInt("meeting_id");
        MeetingsMeeting.dao.delMeetingsmeetingById(meeting_id);
        renderJson(Ret.ok("code", 0).set("message", "返回成功"));
    }

    /**
     * 参加会议
     * {"data":{"id":5,
     * "user":{"id":1,"nickname":"孔令宝-携宁科技","avatarurl":"https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJBYseJziapAgJZTBWMvUUKa4k9ia4Xf747FMGKlm8NDCxcvlwPBatofxRLGXaYCvQXCdn1ziae3S6Tg/132","need_refresh":false},
     * "room":{"id":1,"name":"121","description":"1212"},
     * "date":"2019-10-14","start_time":"09:00:00","end_time":"11:00:00",
     * "attendees":[],
     * "name":"huiyi1","description":"deschuiyi","is_manager":true},
     * "code":0,"message":"返回成功"}
     */
//    @ActionKey("/api/meeting/join?meeting_id=4")
    @ActionKey("/api/meeting/join")
    public void meeting_join() {
        Integer userid = getCurrentUserId();
        Integer meeting_id = getParaToInt("meeting_id");
        MeetingsMeetingattendee meetingsMeetingattendee = new MeetingsMeetingattendee();
        meetingsMeetingattendee.setUserId(userid);
        meetingsMeetingattendee.setMeetingId(meeting_id);
        meetingsMeetingattendee.setModifyTime(new Date());
        meetingsMeetingattendee.save();
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", meetingsMeetingattendee));
    }

    /**
     * 取消参加会议
     * {"data":{"id":5,
     * "user":{"id":1,"nickname":"孔令宝-携宁科技","avatarurl":"https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJBYseJziapAgJZTBWMvUUKa4k9ia4Xf747FMGKlm8NDCxcvlwPBatofxRLGXaYCvQXCdn1ziae3S6Tg/132","need_refresh":false},
     * "room":{"id":1,"name":"121","description":"1212"},
     * "date":"2019-10-14","start_time":"09:00:00","end_time":"11:00:00",
     * "attendees":[],
     * "name":"huiyi1","description":"deschuiyi","is_manager":true},
     * "code":0,"message":"返回成功"}
     */
//    @ActionKey("/api/meeting/leave?meeting_id=17500")
    @ActionKey("/api/meeting/leave")
    public void meeting_leave() {
        Integer userid = getCurrentUserId();
        Integer meeting_id = getParaToInt("meeting_id");
        MeetingsMeetingattendee meetingsMeetingattendee = MeetingsMeetingattendee.dao.findMeetingsmeetingattendee(meeting_id, userid);
        meetingsMeetingattendee.setDeleteStatus(true);
        meetingsMeetingattendee.update();
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", meetingsMeetingattendee));
    }

    /**
     * 根据key,value获取列表
     */
    @ActionApi(remark = "枚举获取")
    @Params({
            @Param(name = "key", remark = "枚举key", defaultValue = "classtype", required = true),
            @Param(name = "value", remark = "枚举value", defaultValue = "")
    })
    @ActionKey("/api/meeting/enum")
    public void meeting_enum() {
        Integer userid = getCurrentUserId();
        String key = getPara("key");
        String value = getPara("value");
        List<Record> records = MeetingEnum.dao.findMeetingenumList(key,value);
        if("array".equals(getPara("type"))){
            List<String> list = new ArrayList<>();
            for(Record record: records){
                list.add(record.get("name"));
            }
            renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data",list.toArray(new String[0])));
            return;
        }

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data",records));
    }


}
